package com.zhx.real.mybatisplus.util;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.dozer.Mapper;
import org.dozer.MappingException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.LinkedList;
import java.util.List;

/**
 * Dozer mapper 转换工具类
 *
 * @author Jerry.Wu on 2018/5/21
 */
@Component
public class DozerMapperUtils {

    @Autowired
    private Mapper dozerBeanMapper;

    /**
     * Constructs new instance of destinationClass and performs mapping between from source
     *
     * @param source
     * @param destinationClass
     * @param <T>
     * @return
     * @throws MappingException
     */
    public <T> T map(Object source, Class<T> destinationClass) throws MappingException {
        return dozerBeanMapper.map(source, destinationClass);
    }

    /**
     * Performs mapping between source and destination objects
     *
     * @param source
     * @param destination
     * @throws MappingException
     */
    public void map(Object source, Object destination) throws MappingException {
        dozerBeanMapper.map(source, destination);
    }


    /**
     * Constructs new instance of destinationClass and performs mapping between from source
     *
     * @param source
     * @param destinationClass
     * @param mapId
     * @param <T>
     * @return
     * @throws MappingException
     */
    public <T> T map(Object source, Class<T> destinationClass, String mapId) throws MappingException {
        return dozerBeanMapper.map(source, destinationClass, mapId);
    }

    /**
     * Performs mapping between source and destination objects
     *
     * @param source
     * @param destination
     * @param mapId
     * @throws MappingException
     */
    public void map(Object source, Object destination, String mapId) throws MappingException {
        dozerBeanMapper.map(source, destination, mapId);
    }

    public <T> List<T> mapList(List sourceList, Class<T> destinationClass) {
        List<T> destinationList = new LinkedList<>();
        for (Object sourceObject : sourceList) {
            T destinationObject = dozerBeanMapper.map(sourceObject, destinationClass);
            destinationList.add(destinationObject);
        }
        return destinationList;
    }

    public <PO, VO> Page<VO> mapperPage(Page<PO> page, Class<VO> voClass) {
        List<PO> pos = page.getRecords();
        List<VO> vos = mapList(pos, voClass);

        Page<VO> pageVO = new Page<>();
        page.setRecords(null);
        map(page, pageVO);
        pageVO.setRecords(vos);
        return pageVO;
    }

}
